package com.jiajia.study.socket;

import java.io.IOException;
import java.net.*;

/**
 *
 * udp客户端
 * @author : zjj
 * @date : 2021-04-19 15:15
 */
public class UDPClient {

    public static void main(String[] args) throws IOException {
        //ServerTest();

        ClientTest();



    }

    /**
     * 发送端
     */
    private static void ClientTest() throws IOException {
        // udp
        DatagramSocket socket = new DatagramSocket();

        String str = "udp测试数据udp测试数据udp测试数据udp测试数据udp测试数据udp测试数据";
        byte[] data = str.getBytes();
        // 数据报
        DatagramPacket packet = new DatagramPacket(data,0,data.length,InetAddress.getLocalHost(),9000);
        // 发送消息
        socket.send(packet);

        socket.close();
    }

    /**
     * 接收端
     */
    public static void ServerTest() throws IOException {
        // 点对点连接，与服务端
        DatagramSocket socket = new DatagramSocket(9000);

        byte[] buffer = new byte[1024 * 1024];
        // 数据报
        DatagramPacket datagramPacket = new DatagramPacket(buffer,0,buffer.length);

        // 接收数据
        socket.receive(datagramPacket);

        System.out.println(new String(datagramPacket.getData(),0,datagramPacket.getLength()));

        socket.close();
    }
}
